import {config} from "../config/config"
import {promisic} from "../utils/util"
import {Http} from "../utils/http"

class Token {
    url
    tokenUrl

    constructor() {
        this.url = config.apiBaseUrl + "/users"
        this.tokenUrl = config.apiBaseUrl + "/users/oauth"
    }

    async verify() {
        const token = wx.getStorageSync('token')
        if (!token) {
            this.getTokenFromServer()
        }
    }

    async _getOpenId(code) {
        // const code = await this._getCode()
        const res = await promisic(wx.request) ({
            url: this.url,
            data: {
                code
            },
            method: 'POST'
        })
        return res.data
    }

    async _getCode() {
        const r = await wx.login()
        return r.code
    }

    async getTokenFromServer() {
        const code = await this._getCode()
        const o = await this._getOpenId(code)
        const res = await promisic(wx.request)({
            url: this.tokenUrl,
            method: 'POST',
            data: {
                openid: o.openid
            }
        })
        wx.setStorageSync('token', res.data.data.tk)
        wx.setStorageSync('user', res.data.data.user)
    }
    async decodeFromServer(ed,iv, code) {
        const o = await this._getOpenId(code)
        const sk = o.session_key
        return await Http.request({
            url: '/users/decode',
            data: {
                encryptedData: ed,
                session_key: sk,
                iv
            },
            method: 'POST'
        })
    }
}
export {
    Token
}
